<?php
	session_start();
	include_once 'KLogger.php';
	
	if(!isset($logger))
		$logger = new KLogger ( "log/vocabolario.log" , KLogger::DEBUG );

	$sTable = "ajax";
    
    // TODO usare basic autentication
	$urlxml = "protected/config.xml";
	$config= new SimpleXmlElement($urlxml,1,true);
    $host = $config->connection->host;
    $port = $config->connection->port;
    $database = $config->connection->database;
    $user = $config->connection->user;
    $pass = $config->connection->password;
	
    $uid = $_SESSION['uid'];
    
	$output = array(
		"sEcho" => intval($_POST['sEcho']),
		"iTotalRecords" => 0,
		"iTotalDisplayRecords" => 0,
		"aaData" => array()
	);
    
	$sLimit = "";
	
	$iDisplayStart = 0 ;
	$iDisplayLength = 10;
	
	if ( isset( $_POST['iDisplayStart'] ) && $_POST['iDisplayLength'] != '-1' ){
		$iDisplayStart = $_POST['iDisplayStart'] ;
		$iDisplayLength = $_POST['iDisplayLength'];
		$sLimit = "LIMIT  $iDisplayStart , $iDisplayLength";
	}
	
	$sWhere = "WHERE uid=".$uid;

	if ( isset($_POST['sSearch']) && $_POST['sSearch'] != "" ){
		$sWhere .= " and ( parola LIKE '%".$_POST['sSearch']."%' ";
		$sWhere .=" )";
	}
    
	$logger->LogDebug("where:".$sWhere);
    
	try {
	    $connection =  "mysql:host=$host;port=$port;dbname=$database";
		$db = new PDO($connection , $user, $pass);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$db->exec("SET CHARACTER SET utf8");
		$query="SELECT count(*) 
    		  FROM vocabolario
    		  $sWhere ";
              
		$stm = $db->query($query);   
		$iTotal = $stm->fetchColumn();
		$output['iTotalRecords']=$iTotal;
		// mysql non ha la fn row_count() , usata variabile in query singola
        $query = "SELECT @n:=@n+1 AS n, parola, definizione , id
            FROM vocabolario  , (select @n:=$iDisplayStart ) r
            $sWhere 
            order by id DESC
            $sLimit ;";
		
        $logger->LogDebug("query:\n".$query);
        
		$stm = $db->query($query);
		$iFilteredTotal=$stm->rowCount();
		$output['iTotalDisplayRecords']=$iTotal;
		$stm->setFetchMode(PDO::FETCH_NUM);
		foreach($stm as $row) {
			array_push($output['aaData'],$row);
		}
		//$logger->LogDebug(print_r($output,true));
		$db = null;
	} catch (PDOException $e) {
		$logger->LogDebug("Error:".$e->getMessage());
	}
	//error_log(print_r($output,true));
	echo utf8_encode(json_encode( $output ));
?>